package com.example.demo.service.imp;


import com.example.demo.entity.rep.RuleRep;
import com.example.demo.mapper.RuleMapper;
import com.example.demo.service.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Log4j2
@Service
public class ScheduleServiceImp implements ScheduleService {
    @Autowired
    private RuleService ruleService;

    @Autowired
    private RuleMapper ruleMapper;

    @Autowired
    private EsSearchService esSearchService;

    @Autowired
    private SqlSearchService sqlSearchService;

//    @Override
//    public void init() {
//        List<RuleRep> rules = ruleService.getAll();
//    }


    @Override
    public void executeTask() {
        List<RuleRep> list = ruleService.getAll();
        long currentTime = System.currentTimeMillis();
        list.forEach(ruleRep -> {
            if (isExecute(ruleRep, currentTime)) {
//                如果需要执行，则更新执行时间
                ruleMapper.updateLastUpdateTime(ruleRep.getUuid(), System.currentTimeMillis());
                switch (ruleRep.getRuleType()) {
                    case 4:
//                        执行sql任务
                        sqlSearchService.searchDataFromSql(ruleRep);
                        break;
                    case 3:
//                        执行es任务
                        esSearchService.searchDataFromEs(ruleRep);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * 判断是否需要执行
     * @param ruleRep
     * @param currentTime
     * @return
     */
    public boolean isExecute(RuleRep ruleRep, long currentTime) {
        long lastExecutionTime = ruleRep.getLastExecutionTime();
        long interval = (long) ruleRep.getTimeValue() * ruleRep.getTimeUnit();
        return currentTime - lastExecutionTime >= interval && ruleRep.getStatus();
    }
}
